<?
include dirname(__FILE__)."/../../global.php";

include dirname(__FILE__)."/css.php";
?>

<script language='javascript'>
function comments_show(link) {
	document.getElementById(link+"-comments").innerHTML = document.getElementById(link+"-content").innerHTML;
	}
</script>

<?

function _docs_comments($link) {
	global $db;

	$r = $db->query("select docscomment.*, users.title as users_title from docscomment ".
		" left join users on users.id = docscomment.users_id ".
		" where link = ".$db->sqlstring($link).
		" order by datetimeon desc ".
		"");
	$n = count($r);

	echo "<form class='addcomment' action='comment_new.php'><input type='hidden' name='link' value='$link'><input type='submit' value='Add a Comment'></form>";
	
	if (!$n) return $n;
	
	echo "<table class='comments'>";
	if (!count($r)) { #NOTE: deprecated, but here in case i change my mind
		echo "<tr><th>No users comments have been submitted.";
		}
	foreach ($r as $e) {
		if (!$e["users_title"]) $e["users_title"] = "Anonymous";
		echo "<tr><th>".date("F j, Y g:ia",strtotime($e["datetimeon"]));
		echo " - ".htmlentities($e["users_title"]);
		echo "<tr><td><pre>".htmlentities($e["content"])."</pre>";
		}
	echo "</table>";
	
	echo "<form class='addcomment' action='comment_new.php'><input type='hidden' name='link' value='$link'><input type='submit' value='Add a Comment'></form>";

	return $n;	
	}
	
function _docs_comments_callback($m) {
	global $db;
	$link = $m[1];

	ob_start();
	$n = _docs_comments($link);
	$content = ob_get_contents();
	ob_end_clean();

	if ($_SESSION["docs_comments_show"] || $_REQUEST["link"] == $link || $n == 0) return $content;
		
	ob_start();
	echo "<div id='$link-content' style='display:none;'>$content</div>";
	echo "<div id='$link-comments'>";
	echo "<input type='button' value='Comments ($n)' onclick='comments_show(\"$link\");'>";
	echo "</div>";
	$content = ob_get_contents();
	ob_end_clean();

	return $content;
	}

	
ob_start();
if (isset($_REQUEST["comments_show"])) {
	$_SESSION["docs_comments_show"] = $_REQUEST["comments_show"];
	}
if ($_SESSION["docs_comments_show"]) {
	echo "<form style='margin:0px;padding:0px;'><input type='hidden' name='comments_show' value=0><input type='submit' value='Hide All Comments'></form>";
} else {
	echo "<form style='margin:0px;padding:0px;'><input type='hidden' name='comments_show' value=1><input type='submit' value='Show All Comments'></form>";
	}
$show_content = ob_get_contents();
ob_end_clean();
	
$docsdir = ".";
foreach (file($docsdir.$_SERVER["PATH_INFO"]) as $line) {
	if ($show_content && stristr($line,"</table>")) {
		$line.="<div>&nbsp;</div>$show_content";
		$show_content =0;
		}
	
	echo preg_replace_callback("/\<\!\-\-COMMENTS\:(.*?)\-\-\>/",_docs_comments_callback,$line);
	

	}

?>